package com.example.bootintegration.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Quintoy
 * @date 2024/7/16
 */
@Service
public class RedisTemplateTest implements ApplicationRunner {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;




    @Override
    public void run(ApplicationArguments args) throws Exception {
        redisTemplate.opsForValue().set("a", "d", 1);
        // for (int i = 0; i < 1000; i++) {
        //     redisTemplate.opsForValue().set("ab" + i, "value" + i);
        //     if (i > 500) {
        //         redisTemplate.opsForValue().set("key" + i, "value" + i);
        //     }
        // }
    }

    public void clearCache() {
        // redisTemplate.executePipelined((RedisCallback) connection -> {
        //     // connection.del("fs");
        //     return null;
        // });

        // RedisConnection connection1 = redisTemplate.getConnectionFactory().getConnection();
              redisTemplate.executeWithStickyConnection(connection -> {
            Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().count(1000).match("ab*").build());
            // connection.openPipeline();
            List<byte[]> item = new ArrayList<>();
            while (cursor.hasNext()) {
                // connection.del(cursor.next());
                item.add(cursor.next());
            }
            Long del = connection.del(item.toArray(new byte[0][]));
            System.out.println(del);
            // List<Object> objects = connection.closePipeline();
            // System.out.println(objects);
            return null;
        });

        // Integer deletedKeyCount = redisTemplate.execute(connection -> {
        //     int count = 0;
        //     Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().count(1000).match("key*").build());
        //     while (cursor.hasNext()) {
        //         Long del = connection.del(cursor.next());
        //         System.out.println(del);
        //
        //     }
        //     return count;
        // }, true, true);
    }
}
